﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using BdsSoft.DirectoryServices.Linq;
using System.IO;

namespace 顔写真いじったー
{
    class PhotoWrapper
    {
        private string _UserName;
        public string UserName { set { _UserName = value; } get { return _UserName; } }

        private string _DomainName;
        public string DomainName { set { _DomainName = value; } get { return _DomainName; } }

        private byte[] _ThumbnailPhoto;
        public byte[] ThumbnailPhoto { set { _ThumbnailPhoto = value; } get { return _ThumbnailPhoto; } }

        private string _DisplayName;
        public string DisplayName { get { return _DisplayName; } }

        public PhotoWrapper()
        {
            _UserName = "";
            _DomainName = "";
            _DisplayName = "";
            _ThumbnailPhoto = null;
        }

        public PhotoWrapper(string username, string domainname)
        {
            _UserName = username;
            _DomainName = domainname;
            _DisplayName = "";
            _ThumbnailPhoto = null;
        }
    
        public byte[] GetThumbnailPhoto()
        {
            var myusers = new DirectorySource<MyUser>(new DirectoryEntry("LDAP://" + _DomainName), SearchScope.Subtree);

            foreach (var currentuser in myusers.Where(u => u.AccountName == _UserName))
            {
                _DisplayName = currentuser.DisplayName;
                if (currentuser.ThumbnailPhoto == null)
                {
                    _ThumbnailPhoto = null;
                }
                else
                {
                    using (MemoryStream stmBLOBData = new MemoryStream(currentuser.ThumbnailPhoto))
                    {
                        long leng = stmBLOBData.Length;
                        _ThumbnailPhoto = new byte[leng];
                        stmBLOBData.Read(_ThumbnailPhoto, 0, (int)leng);
                    }
                }
                break;
            }

            return _ThumbnailPhoto;
        }

        public void SetThumbnailPhoto(byte[] newImage)
        {
            var myusers = new DirectorySource<MyUser>(new DirectoryEntry("LDAP://" + _DomainName), SearchScope.Subtree);

            foreach (var currentuser in myusers.Where(u => u.AccountName == _UserName))
            {
                currentuser.ThumbnailPhoto = newImage;
                myusers.Update();
                break;
            }
        }

        public void ClearThumbnailPhoto()
        {
            SetThumbnailPhoto(null);
        }
    }
}
